<?php

namespace App\Admin\Controllers;

use App\Admin\Extensions\GuildHostOp;
use App\Http\Controllers\Controller;
use App\Model\Guild\Guild;
use App\Model\Guild\GuildHost;
use App\Model\GuildManage;
use App\Model\UserProfile;
use App\Model\UserProfilePersonal;
use App\Util\InfoUtil;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Layout\Content;

/**
 * 代理女用户管理
 */
class GuildHostController extends Controller
{
    use ModelForm;

    protected $scrtPhone = true;

    /**
     * Index interface.
     *
     * @return Content
     */

    public function index()
    {
        $this->userRole = Admin::user()->roles[0]['slug'];
        $adminId = Admin::user()->id;
        if( Admin::user()->id == 48){
            return [];
        }
        // $this->scrtPhone = in_array($adminId, [7, 10]);
        return Admin::content(function (Content $content) use ($adminId) {
            $content->header('推广成员列表');
            // $content->description("Uid:{$this->scrtPhone}");
            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {
            $content->header('代理详情');
            $content->description('');
            $content->body($this->form('edit', $id)->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {
            $content->header('绑定代理女用户');
            $content->description('');
            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(GuildHost::class, function (Grid $grid) {
            $self = $this;

            $adminId = Admin::user()->id;
           if($adminId == 48 || in_array($adminId,[49,50,51])){
                $guidIds = GuildManage::getGuidIdByAdminId($adminId);
                $grid->model()->whereIn('guild_manage_id',$guidIds);
            }


            $grid->model()->orderBy('id', 'desc');
            $grid->created_at('签约时间')->display(function ($time) {
                return !$time ? '-' : date('Y-m-d H:i', strtotime($time));
            });
            $grid->guildInfo()->name('代理名');
            $grid->guildInfo()->guild_id('代理ID');
            // $grid->hostInfo()->user_profile_id('女用户ID');
            $grid->host_profile_id('女用户ID');
            $grid->hostInfo()->nick_name('女用户昵称');
            $grid->hostInfo()->gender('性别')->display(function ($data) {
                return $data == 1 ? '男' : '女';
            });
            $grid->hostUserInfo()->phone('手机号')->display(function ($data) use ($self) {
                if (!$data) return '-';
                return $self->scrtPhone ? mb_substr($data, 0, 3) . '****' . mb_substr($data, -4) : $data;
            });
            $grid->verf_status('实名认证')->display(function ($data) {
                return $data == 1 ? '已认证' : '-';
            });
            $grid->consume_coin('消费总流水')->sortable();
            $grid->status('状态')->display(function ($data) {
                return $data == 1 ? '签约中' : '已退会 （' . (string)$this->unbind_at . '）';
            });

            //禁用导出
//            $grid->disableExport();
            //禁用行选择
            $grid->disableRowSelector();
            if ($this->userRole != 'administrator') {
//                $grid->disableCreateButton();
            }
            $permissionsBtUid = config('busi.permissions_bt_uid');
            if(!in_array(Admin::user()->id,$permissionsBtUid)){
//                $grid->disableCreateButton();
            }

            if(Admin::user()->id == 48 || in_array(Admin::user()->id,[49])){
                $grid->disableCreateButton();
            }

            $grid->filter(function ($filter) {
                $filter->expand();
                $filter->disableIdFilter();
                $filter->column(1 / 4, function ($filter) {
                    $filter->equal('host_profile_id', '女用户ID');
                });
                $filter->column(1 / 4, function ($filter) {
                    $filter->equal('guildInfo.id', '所属代理')->select('/get_guilds');
                });
                $filter->column(1 / 4, function ($filter) {
                    $filter->equal('status', '状态')->select([0 => '已退会', 1 => '签约中']);
                });
            });

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableDelete();
                $actions->disableView();
                $actions->disableEdit();

                //移除操作
                $actions->append(new GuildHostOp(
                    $actions->getKey(),
                    $actions->row,
                    'remove_host'
                ));
            });
        });
    }

    /**
     * Make a form builder.
     * @return Form
     */
    protected function form($mode = '', $id = '')
    {
        return Admin::form(GuildHost::class, function (Form $form) use ($mode, $id) {
            $form->textarea('host_id', '女用户ID')->required();
            // $form->display('host_name', '女用户昵称');
            $form->select('guild_manage_id', '所属代理')->options('/get_guilds')->required();
            //保存前检测
            $form->hidden('host_user_id');
            $form->hidden('verf_status');
            $form->hidden('host_profile_id');
            $form->ignore(['host_id']);
            $form->saving(function (Form $form) {
                $profileIds = explode("\r\n", request('host_id'));
                foreach ($profileIds as $profileId) {
                    $check = UserProfile::where(['user_profile_id' => $profileId])->first();
                    if (!$check) return InfoUtil::adminErr('没有该女用户信息:' . $profileId);
                    //是否绑定过该女用户
                    $hostId = $check->user_id;
                    $check = GuildHost::checkBind($hostId);
                    if ($check) return InfoUtil::adminErr('该女用户已经绑定过了:' . $profileId);
                    if (!in_array($form->guild_manage_id, explode('EXCLUDE_OFFICIAL_GUILD', '107'))) {
                        //清除邀请关系
//                        UserProfile::where('user_profile_id', $profileId)->limit(1)->update(['invite_code' => '']);
                    }
                    $model = new GuildHost();
                    $model->guild_manage_id = $form->guild_manage_id;
                    $model->host_user_id = $hostId;
                    $model->host_profile_id = $profileId;
                    //认证状态
                    $model->verf_status = UserProfilePersonal::isFaceVerified($hostId);
                    $ret = $model->saveOrFail();
                }
                return InfoUtil::adminSuc("绑定成功！");
            });
            $form->ignore(['host_id']);
            $form->tools(function (Form\Tools $tools) {
                $tools->disableList();
                $tools->disableDelete();
                $tools->disableView();
                $tools->disableView();
            });
        });
    }

    /**
     * 移除女用户
     */
    function remove_host()
    {
        $id = request('id');
        $record = GuildHost::find($id);
        if (!$record) return ['ret' => -1, 'message' => '记录不存在'];
        $record->update(['status' => 0, 'unbind_at' => date('Y-m-d H:i:s')]);
        return ['ret' => 0, 'message' => '操作成功！'];
    }

    /**
     * 获取代理列表
     */
    function get_guilds()
    {
        $adminId = Admin::user()->id;
        $flag = false;
       if($adminId == 48 || in_array($adminId,[49,50,51])) $flag = true;
        if($flag){
            $list = Guild::where(['status' => 1,'admin_id'=> $adminId])->select(['name', 'id'])->get()->toArray();
        }else{
            $list = Guild::where(['status' => 1])->select(['name', 'id'])->get()->toArray();
        }

        $data = [];
        foreach ($list as $item) {
            $data[] = ['id' => $item['id'], 'text' => $item['name']];
        }
        return $data;
    }

    /**
     * 获取代理列表
     */
    function get_guilds_all()
    {
        $list = Guild::select(['name', 'id'])->get()->toArray();
        $data = [];
        foreach ($list as $item) {
            $data[] = ['id' => $item['id'], 'text' => $item['name']];
        }
        return $data;
    }
}
